<template>
    <div class="white-box">
        <div>
            <el-button
                v-hasPermi="['enttp:car:add']"
                class="table-mb"
                type="primary"
                @click="onClickAdd"
                >添加车辆</el-button
            >
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">负责人员：</span>
                <el-input
                    placeholder="请输入车辆负责人"
                    v-model="state.cartHead"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">车牌号码：</span>
                <el-input
                    placeholder="请输入车牌号码"
                    v-model="state.cartNumber"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">运输状态：</span>
                <el-select
                    v-model="state.carState"
                    placeholder="请选择状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.carStateList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">车辆状态：</span>
                <el-select
                    v-model="state.status"
                    placeholder="请选择状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:car:del']"
                @click="onClickDel()"
                >批量删除车辆</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                type="selection"
                width="55"
                v-hasPermi="['enttp:car:del']"
            />
            <el-table-column
                prop="carHead"
                label="车辆负责人"
                min-width="200"
                fixed="left"
            ></el-table-column>
            <el-table-column
                prop="carNumber"
                label="车牌号"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                prop="carState"
                label="运输状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("car_state", row.carState) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("data_status", row.status) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickDetails(row.sid),
                                    'v-hasPermi': ['enttp:car:query'],
                                },
                                text: '详情',
                            },
                            {
                                props: {
                                    onClick: () => changeStatus(row.sid),
                                    'v-hasPermi': ['enttp:car:update'],
                                },
                                text: ['停用', '启用'][row.status],
                            },
                            {
                                props: {
                                    onClick: () =>
                                        showChangeCarStateDialog(row),
                                },
                                text: '更改运输状态',
                            },
                            // {
                            //     props: {
                            //         onClick: () => onClickWaybill(row.sid),
                            //     },
                            //     text: '已分配运单',
                            //     isRender: row.carState === 0,
                            // },
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                    'v-hasPermi': ['enttp:car:edit'],
                                },
                                text: '修改',
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:car:del'],
                                },
                                text: '删除',
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-drawer v-model="state.showDetail" title="车辆详情" size="540">
        <template v-if="detail">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">负责人</el-col>
                <el-col :span="18">{{ detail.carHead }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">车牌号</el-col>
                <el-col :span="18">{{ detail.carNumber }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">运输状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("car_state", detail.carState)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">绑定线路</el-col>
                <el-col :span="18">
                    <p v-for="line in detail.lines" :key="line.sid">
                        {{ line.lineName }}
                    </p>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">归属网点</el-col>
                <el-col :span="18">{{ detail.outlet?.outletsName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">备注</el-col>
                <el-col :span="18">{{ detail.note }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("data_status", detail.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">创建时间</el-col>
                <el-col :span="18">{{ detail.created }}</el-col>
            </el-row>
        </template>
    </el-drawer>

    <el-dialog
        v-model="state.showChangeCarState"
        title="更改车辆运输状态"
        width="350"
    >
        <p>运输状态</p>
        <el-radio-group v-model="state.selectedCarState" class="ml-4">
            <el-radio
                v-for="item in state.carStateList.filter(
                    (item) => item.memberKey !== 2
                )"
                :key="item.memberKey"
                :value="item.memberKey"
                >{{ item.memberName }}</el-radio
            >
        </el-radio-group>
        <el-button type="primary" class="w-100% mt-20" @click="changeCarState">
            保存
        </el-button>
    </el-dialog>

    <el-dialog v-model="state.showWaybill" title="已分配运单" width="800">
        <el-table
            class="table-mb"
            v-loading="LoadingWaybill"
            :data="waybills"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            max-height="250"
            size="small"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column
                prop="wayBillCode"
                label="运单流水号"
                min-width="200"
                fixed="left"
            ></el-table-column>
            <el-table-column
                prop="orderId"
                label="订单ID"
                min-width="200"
            ></el-table-column>
            <el-table-column
                prop="note"
                label=" 备注"
                min-width="200"
            ></el-table-column>
        </el-table>
        <el-pagination
            background
            v-model:current-page="pageWaybill"
            v-model:page-size="pageSizeWaybill"
            :page-sizes="pageSizeNumWaybill"
            :total="totalNumsWaybill"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNumsWaybill >= 100 * pageSizeWaybill
                        ? `${100 * pageSize}+`
                        : totalNumsWaybill
                }}&nbsp;条</span
            >
        </el-pagination>
    </el-dialog>
</template>

<script setup>
import { inject, reactive, onMounted, onActivated, toRefs } from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import {
    getCars,
    getCarDetail,
    delCars,
    changeCarStatus,
    getCarLines,
    getCarOutlet,
    changeCarState as changeCarStateApi,
} from "@/apis/enterprise/car.js";
import { getWaybillsByUndeliveredCar } from "@/apis/order/waybill.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore.getDictMembers("car_state").then((res) => (state.carStateList = res));

const router = useRouter();
const $message = inject("$message");

const state = reactive({
    statusList: [],
    carStateList: [],
    ascended: false,
    sortFieldName: null,
    cartNumber: null,
    cartHead: null,
    carState: null,
    status: null,
    sidList: [],
    showDetail: false,
    detail: null,
    showChangeCarState: false,
    selectedCarSid: null,
    selectedCarState: null,
    showWaybill: false,
});

const { detail } = toRefs(state);

onActivated(() => {
    pubParams(getList);
});

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getCars({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            cartNumber: state.cartNumber,
            cartHead: state.cartHead,
            carState: state.carState,
            status: state.status,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 跳转到新增页
const onClickAdd = () => {
    router.push({ name: "CarAdd" });
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

// 点击修改按钮
const onClickEdit = (sid) => {
    sid &&
        router.push({
            name: "CarEdit",
            query: {
                sid,
            },
        });
};

// 跳转详情
const onClickDetails = async (sid) => {
    state.showDetail = true;
    state.detail = null;
    await getDetails(sid);
    // 获取车辆绑定的线路
    getLines(sid);
    // 获取车辆绑定的网点
    getOutlets(sid);
};

const getDetails = async (sid) => {
    const res = await getCarDetail({ sid });
    if (res.data.code == 200) {
        state.detail = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getLines = async (sid) => {
    const res = await getCarLines({ sid });
    if (res.data.code == 200) {
        state.detail.lines = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getOutlets = async (sid) => {
    const res = await getCarOutlet({ sid });
    if (res.data.code == 200) {
        state.detail.outlet = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 显示修改车辆运输状态弹窗
const showChangeCarStateDialog = ({ sid, carState }) => {
    state.showChangeCarState = true;
    state.selectedCarSid = sid;
    state.selectedCarState = carState;
};

// 更改车辆运输状态
const changeCarState = async () => {
    const res = await changeCarStateApi({
        sid: state.selectedCarSid,
        carState: state.selectedCarState,
    });
    if (res.data.code == 200) {
        $message({ message: "修改成功", type: "success" });
        state.showChangeCarState = false;
        state.selectedCarSid = null;
        state.selectedCarState = null;
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 点击启用/停用按钮
const changeStatus = async (sid) => {
    const res = await changeCarStatus({ sid });
    if (res.data.code == 200) {
        $message({ message: "操作成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 选中项改变
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除车辆吗？");
    const res = await delCars({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const onClickWaybill = (sid) => {
    state.showWaybill = true;
    if (sid !== state.selectedCarSid) {
        state.selectedCarSid = sid;
        pubRefreshParamsWaybill(getListWaybill);
    } else {
        pubParamsWaybill(getListWaybill);
    }
};

const {
    loading: LoadingWaybill,
    arr_data: waybills,
    pubRefreshParams: pubRefreshParamsWaybill,
    pubParams: pubParamsWaybill,
    page: pageWaybill,
    pageSize: pageSizeWaybill,
    getdata: getdataWaybill,
    pageSizeNum: pageSizeNumWaybill,
    totalNums: totalNumsWaybill,
    openPaging: openPagingWaybill,
} = OneLoad();

openPagingWaybill(getListWaybill);

function getListWaybill() {
    getdataWaybill(
        getWaybillsByUndeliveredCar({
            current: pageWaybill.value,
            size: pageSizeWaybill.value,
            carSid: state.selectedCarSid,
        })
    );
}
</script>

<style lang="less" scoped></style>
